#include<iostream>

#include<mysql/mysql.h>

#include<string>

int main()
{
    // printf("mysql client version: %s\n", mysql_get_client_info());

    MYSQL* mfp = mysql_init(nullptr);

    if(!mfp)
    {
        std::cerr << "mysql_init error" << std::endl;
    }

    MYSQL* conn = mysql_real_connect(mfp, "localhost", "thx", "thxTHX@2580", "db5", 0, nullptr, 0);

    mysql_set_character_set(mfp, "utf-8");

    if(!conn)
    {
        std::cerr << "mysql_real_connect error" << std::endl;
    }

    std::string input;
    while(1)
    {
        std::cout << "mysql> ";
        if(getline(std::cin, input) && input != "quit")
        {
            int ret = mysql_query(mfp, input.c_str());

            // std::cout << "行数: " << mysql_num_rows(res) << std::endl;

            // std::cout << "列数: " << mysql_num_fields(res) << std::endl;

            if(ret != 0)
            {
                std::cerr << "mysql_query error" << std::endl;
            }

            MYSQL_RES* res = mysql_store_result(mfp);

            if(res)
            {
                my_ulonglong rownum = mysql_num_rows(res);
                unsigned int fieldnum = mysql_num_fields(res);
            
                MYSQL_FIELD* fields = mysql_fetch_fields(res);
            
                for(int i = 0; i < fieldnum; ++i)
                    std::cout << fields[i].name << "\t";
                std::cout << std::endl;
            
                for(int i = 0; i < rownum; ++i)
                {
                    MYSQL_ROW rows = mysql_fetch_row(res);
                    for(int j = 0; j < fieldnum; ++j)
                    {
                        std::cout << rows[j] << "\t";
                    }
                    std::cout << std::endl;
                }
                mysql_free_result(res);
            }
        }
        else
        {
            std::cout << "Bye" << std::endl;
            break;
        }
    }

    mysql_close(mfp);
    return 0;
}